template.defaults.imports.CountdownTime = function (factEndDate) {
    var timestamp = (new Date()).valueOf();
    return factEndDate - timestamp;
};

template.defaults.imports.FileAutoTrans = function (fileName) {
    var suffix = get_suffix(fileName);
    var filePath = '';
    switch (suffix.toUpperCase()) {
        case '.MP4':
            filePath = fileName + '?x-oss-process=video/snapshot,t_1,f_jpg,w_500';
            break;
        case '.MOV':
            filePath = '/img/Audio_and_Video_018.png';
            break;
        default:
            filePath = fileName + '?x-oss-process=image/resize,w_400';
            break;
    }
    return filePath;
};

function get_suffix(filename) {
    pos = filename.lastIndexOf('.')
    suffix = ''
    if (pos != -1) {
        suffix = filename.substring(pos)
    }
    return suffix;
}

$(function () {
    //******************* start 排序条件及其筛选条件框 ***********************/
    $('.weui-flex__item').click(function () {
        $('.weui-flex__item').removeClass('current');
        $(this).addClass('current');
        var display = $(this).find('.children').css('display');
        if (display == 'none') {
            $(this).find('.children').show();
        } else {
            $(this).find('.children').hide();
        }

        var type = parseInt($(this).attr('orderType'));
        if (type) {
            orderType = type;
            queryList(function () {}, false);
        }
    });

    $('.weui-flex__item .children .item').click(function () {
        $('.weui-flex__item .children .item').removeClass('current');
        $(this).addClass('current');
        var selectName = $(this).find('text').text();
        var _parent = $(this).parent().parent();
        _parent.addClass('current');
        _parent.find('.placeholder text').text(selectName);
        orderType = parseInt($(this).attr('orderType'));
        queryList(function () {}, false);
    });

    $('.mask').click(function () {
        closeAll();
    });
    $('#screen').click(function () {
        $('.mask').show();
        $('.screen_condition').show().animate({
            right: '0'
        });
    });

    $(window.document.body).click(function (e) {
        var target = $(e.target);
        var isHide = true;
        while (target.prop("tagName")) {
            if (target.hasClass('weui-flex__item')) {
                isHide = false;
                break;
            } else {
                target = target.parent();
            }
        }
        if (isHide)
            $('.weui-flex__item .children').hide();
    });

    //带条件和分类查询
    $('#screen_condition_confirm').click(function () {
        keyword = $('.screen_condition .item .list input[name="keyword"]').val();
        queryList();
        closeAll();
    });
    $('#screen_condition_reset').click(function () {
        resetCondition();
    });

    function closeAll() {
        $('.mask').hide();
        $('.weui-flex__item .children').hide();
        $('.screen_condition').css({
            right: '-6.2rem'
        }).hide();
    }
    //******************* end 排序条件及其筛选条件框 ***********************/

    var loading = false; //状态标记
    var hasNextPage = false;
    var pageNo = 1;
    var orderType = 1;
    var keyword = false;
    queryList();

    //下拉刷新
    $("#weipai").pullToRefresh().on("pull-to-refresh", function () {
        $("#weipai-list-content .left-list").html("");
        $("#weipai-list-content .right-list").html("");
        resetCondition();
        queryList(function () {
            $("#weipai").pullToRefreshDone(); // 重置下拉刷新
        });
        return false;
    });

    //上拉加载更多
    $('#weipai').infinite().on("infinite", function () {
        if (hasNextPage) {
            pageNo++;
            queryList(function () {}, true);
        }
    });

    //复位所有参数
    /* global cate1 resetCate cate2 attrs*/
    function resetCondition() {
        pageNo = 1;
        resetCate();
        keyword = false;
        $('.screen_condition .item .list .unit').removeClass('current');
        $('.screen_condition .item .list input[name="keyword"]').val('');
    }

    function queryList(callback, isMore) {
        if (loading) return;
        loading = true;
        var attrsStr = '';
        for (var i = 0; i < attrs.length; i++) {
            if (i == attrs.length - 1) {
                attrsStr += attrs[i];
            } else {
                attrsStr += attrs[i] + ',';
            }
        }
        $.post('/antique/api/mallProduct/web/query_list', {
            start: (pageNo - 1) * 20,
            limit: 20,
            queryType: 1,
            orderType: orderType,
            name: keyword ? keyword : '',
            firstCategorys: cate1 ? cate1 : '',
            secondCategorys: cate2 ? cate2 : '',
            tags: attrsStr
        }, function (result) {
            var leftList = [];
            var rightList = [];
            if(result.data.list){
                for(var i = 0;i<result.data.list.length;i++){
                    if(i%2 == 0){
                        leftList.push(result.data.list[i]);
                    } else {                        
                        rightList.push(result.data.list[i]);
                    }
                }
            }
            if (!isMore) {
                /* global template */
                document.getElementById('left-list-content').innerHTML = template('left-list', {list:leftList});
                document.getElementById('right-list-content').innerHTML = template('right-list', {list:rightList});
            } else {
                $('#left-list-content').append(template('left-list', {list:leftList}));
                $('#right-list-content').append(template('right-list', {list:rightList}));
            }
            $('.weipai-list .lot .info .price .time time[sign="unmake"]').each(function () {
                $(this).removeAttr('sign');
                /* global Countdown */
                Countdown($(this).attr('time'), $(this));
            });
            hasNextPage = result.data.hasNextPage;
            if (!result.data.hasNextPage) {
                $('#loadmore').hide();
                $('#nomore').show();
            } else {
                $('#loadmore').show();
                $('#nomore').hide();
            }
            if (callback) callback();
            loading = false;
        });
    }

    //设置分享
    $.post('/antique/api/wxApi/getticket', {
        url: window.location.href
    }, function (result) {
        //access_token = result.data.access_token;
        wx.config({
            debug: false,
            appId: result.data.appid,
            timestamp: result.data.timestamp,
            nonceStr: result.data.noncestr,
            signature: result.data.signature,
            jsApiList: [
                // 所有要调用的 API 都要加到这个列表中
                'onMenuShareTimeline', 'onMenuShareAppMessage','onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone'
            ]
        });
        wx.ready(function () {
            wx.checkJsApi({
                jsApiList: [
                    'onMenuShareTimeline', 'onMenuShareAppMessage','onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone'
                ],
                success: function (res) {
                    //alert(JSON.stringify(res));
                    //alert(JSON.stringify(res.checkResult.getLocation));
                    if (res.checkResult.getLocation == false) {
                        alert('你的微信版本太低，不支持微信JS接口，请升级到最新的微信版本！');
                        return;
                    } else {
                        // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，
                        // 则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
                        //分享到朋友圈
                        wx.onMenuShareTimeline({
                            title:'古今在线', // 分享标题
                            link:window.location.protocol + '//' +window.location.host, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                            desc: '您身边的宝盒子，交易简单，轻松购，一手掌握。', // 分享描述
                            success: function () {
                                // 用户点击了分享后执行的回调函数
                            },
                        });
                        //分享给朋友
                        wx.onMenuShareAppMessage({
                            title:'古今在线', // 分享标题
                            link:window.location.protocol + '//' +window.location.host, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                            desc: '您身边的宝盒子，交易简单，轻松购，一手掌握。', // 分享描述
                            success: function () {
                                // 用户点击了分享后执行的回调函数
                            }
                        });
                    }
                }
            });
        });
        wx.error(function (res) {
            // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
            alert("验证失败，请重试！");
            wx.closeWindow();
        });
    });
});